/*
 * @Author: qiuziz
 * @Date: 2017-08-18 14:50:56
 * */


import React, { Component } from 'react';
import { Flex, InputItem, Button, NavBar, Toast } from 'antd-mobile';
import './index.scss';
import { Resource } from '../../service/resource';
import BrowserUtils from '../../service/history';
import LocalStorage from '../../service/LocalStorage';

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {
        name: '',
        password: ''
      }
    }
  }
  // componentDidMount() {
  // }

  inputChange(value, type) {
    const { user } = this.state;
    user[type] = value;
    this.setState({user});
  }

  login() {
    const { user } = this.state;
    Resource.login.post({username: user.name, password: user.password}).then(res => {
      if (res && res.status === 1) {
        LocalStorage.setItem('user', user);
        BrowserUtils.replace({pathname: '/home'})
      } else if (res.result === 0) {
        Toast.fail('用户名或密码错误', 2);
      }
    }).catch(err => {
      Toast.fail('登录错误', 2);
      console.log(err)
    })
  }

  render() {
    const { user } = this.state;
    return (
      <Flex className="login" direction="column" align="start" style={{display: this.props.display}}>
        <Flex className="content" direction="column" align="center">
        <NavBar
        mode="dark"
        className="am-tab-bar-bar"
        style={{top: 0, width: '100%', marginBottom: "200px"}}
        iconName={false}
        >
        用户登录
      </NavBar>
          <Flex className="inputItem login_top" justify="between">
            <InputItem
              className="input"
              value={user.name}
              clear
              placeholder="用户名"
              onChange={value => this.inputChange(value, 'name')}
              >
              <div style={{ backgroundImage: 'url("./user_name.svg")', backgroundSize: 'cover', height: '0.44rem', width: '0.44rem', color: '#ccc'}} />
              </InputItem>
          </Flex>
          <Flex className="inputItem" justify="between">
            <InputItem
              className="input"
              type="password"
              value={user.password}
              clear
              placeholder="密码"
              onChange={value => this.inputChange(value, 'password')}
              >
              <div style={{ backgroundImage: 'url("./lock.svg")', backgroundSize: 'cover', height: '0.44rem', width: '0.44rem', color: '#ccc' }} />
          </InputItem>
          </Flex>
          <Flex className="inputItem" justify="around">
            <Button className="btn" type="primary" onTouchTap={() => this.login()}>
              登录
            </Button>
          </Flex>
        </Flex>
      </Flex>
    );
  }
}

